<template>
    <div>
        <el-button type="primary" text @click="handleVisible(true)" :disabled="disabled || !goodIds || !goodIds.length"
            >批量设置积分</el-button
        >
        <el-dialog class="batch_spec_template_dialog" title="批量设置" v-model="visible" width="400px" append-to-body>
            <el-form :model="form" :rules="rules" ref="formRef" @submit.prevent>
                <el-form-item prop="givePoints">
                    每消费1元，赠送<el-input-number
                        v-model="form.givePoints"
                        class="custom-number-small"
                        :min="1"
                        :max="99999999"
                        :precision="0"
                        :controls="false" />积分
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="flex: auto">
                    <el-button plain @click="handleVisible(false)">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, unref } from 'vue';
import { cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import request from '@/request';

const emit = defineEmits(['handle-confirm']);

const props = defineProps({
    goodIds: {
        type: [Array, Object],
        default: () => []
    },
    disabled: {
        type: Boolean,
        default: false
    }
});

const formRef = ref();

let visible = ref(false);
const form = reactive({
    givePoints: 0
});

const rules = {};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const handleVisible = (isVisible = false) => {
    if (!isVisible) {
        form.givePoints = 0;
    }
    visible.value = isVisible;
};

const handleConfirm = async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            if (!form.givePoints) {
                return ElMessage({
                    type: 'error',
                    message: '积分不能小于1'
                });
            }
            await request('pointsGoodsSave', {
                goodsList: props?.goodIds?.map(goodId => {
                    return {
                        goodId,
                        givePoints: form.givePoints * 100
                    };
                })
            });
            ElMessage({
                type: 'success',
                message: '批量设置成功'
            });
            handleVisible(false);
            emit('handle-confirm');
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};
</script>
<style lang="scss" scoped>
.batch_spec_template_dialog {
    .custom-number-small {
        width: 80px;
        margin: 0 4px 0 4px;
    }
}
</style>
